<template>
	<u-tabbar
		:value="currentVal"
		@change="goToView"
		:border="false"
		:fixed="true"
		:placeholder="true"
		:safeAreaInsetBottom="true"
		:zIndex="99999"
		activeColor="#1786f8"
	>
			<u-badge
				v-if="isLogin"
				type="primary"
				max="999" 
				:value="totalAmount"
				absolute
				:offset="[-2, 250]"
			></u-badge>
		<u-tabbar-item
			v-for="(item, i) in tabbarList"
			:key="i"
			:text="item.text"
			:icon="item.icon"
			:name="item.name"
		>
		
		</u-tabbar-item>
	</u-tabbar>
</template>

<script>
import { cartList , delcart } from '@/api/shopcart.js'
export default {
	name: 'tabbar',
	data() {
		return {
			currentVal: '',
			tabbarList: [
				{ text: '首页', icon: 'home', name: '/pages/index/index' },

				{ text: '分类', icon: 'grid', name: '/mallPage/index/index' },
				{
					text: '购物车',
					icon: 'shopping-cart',
					name: '/mallPage/shopCar/shopCar'
				},
				{
					text: '我的',
					icon: 'account-fill',
					name: '/userPage/index/index'
				}
			],
			isLogin:false,
			cartList:[]
		};
	},
	computed: {
		totalAmount() {
			if(this.isLogin){
				return this.cartList.reduce((total, order) => {
					return total + (order.amount || 0); // 使用 order.amount 计算总和，确保 order.amount 存在
				}, 0);
			}
		}
	},
	mounted() {
		let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
		let curRoute = routes[routes.length - 1].route; //获取当前页面路由
		switch (curRoute) {
			case 'pages/index/index': // 首页
				this.currentVal = '/pages/index/index';
				break;

			case 'userPage/index/index': // 我的
				this.currentVal = '/userPage/index/index';
				break;
			case 'mallPage/index/index': // 分类
				this.currentVal = '/mallPage/index/index';
				break;
			case 'mallPage/shopCar/shopCar': // 分类
				this.currentVal = '/mallPage/shopCar/shopCar';
				break;
			default:
				this.currentVal = '';
				break;
		}
		if(uni.getStorageSync('userInfo')){
			this.isLogin = true
			// cartList().then(res => {
			// 	this.cartList = res.data
			// })
		}else{
			this.isLogin = false
		}
		
		this.getCartList()
		
	},
	methods: {
		getCartList(){
			if(this.isLogin){
				cartList().then(res => {
					this.cartList = res.data
				})
			}
		},
		goToView(e) {
			console.log('ss',e)
			this.currentVal = e;
			let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
			let curRoute = routes[routes.length - 1].route; //获取当前页面路由
			if ('/' + curRoute === e) return;
			uni.redirectTo({
				url: e,
				success() {
					console.log('成功了!');
				},
				fail(err) {
					console.log('失败了' + JSON.stringify(err));
				}
			});
		}
	}
};
</script>

<style lang="scss"></style>